import { Input } from "@alifd/next";
import React from "react";

export default class EditableCell extends React.Component {
    state = {
        innerValue: '',
        editable: false
    }
    constructor(props: {
        value: string
        onChange: any
        editable: boolean
    }) {
        super(props);
        this.onKeyDown = e => {
            const { keyCode } = e;
            if (keyCode == 13) {
                this.setState({
                    editable: false,
                });
                this.props.onChange && this.props.onChange(e.target.value);
            }
            if (keyCode > 36 && keyCode < 41) {
                e.stopPropagation();

            }
        };
        this.onBlur = e => {
            this.setState({
                editable: false,
                innerValue: e.target.value,
            });
            this.props.onChange && this.props.onChange(e.target.value);
        };
        this.onDblClick = () => {
            this.setState({
                editable: true,
            });
        };
        this.state = {
            innerValue: props.value,
            editable: false,
        };
    }
    render() {
        const { editable } = this.state;
        if (editable) {
            return (
                <Input autoFocus value={this.state.innerValue} onKeyDown={this.onKeyDown} onChange={(value) => {
                    this.setState({
                        innerValue: value
                    });
                }} onBlur={this.onBlur} />
            );
        }
        return <span onDoubleClick={this.onDblClick}>{this.state.innerValue}</span>;
    }
}